#include "SkinObjManager.h"
#include "SkinWindowBase.h"
#include <utility>

CSkinObjManager* CSkinObjManager::m_pObjMgr = NULL;
CRITICAL_SECTION CSkinObjManager::m_csHwnd;
std::map<HSKINHWND, CSkinWindowBase*> CSkinObjManager::m_mapObj;
HSKINHWND CSkinObjManager::m_hNextHwnd = NULL;

CSkinObjManager::CSkinObjManager( void )
{
    m_hNextHwnd = NULL;
    ::InitializeCriticalSection( &m_csHwnd );
}

CSkinObjManager::~CSkinObjManager( void )
{
    ::DeleteCriticalSection( &m_csHwnd );
    std::map<HSKINHWND, CSkinWindowBase*>::const_iterator cit;

    for ( cit = m_mapObj.begin(); cit != m_mapObj.end(); cit++ )
    {
        CSkinWindowBase* pSkinObj = cit->second;

        if ( NULL != pSkinObj )
        {
            if ( IsWindow( pSkinObj->GetRealHwnd() ) )
            {
                ::DestroyWindow( pSkinObj->GetRealHwnd() );
            }

            delete pSkinObj;
            pSkinObj = NULL;
        }
    }

    m_mapObj.clear();
}

CSkinObjManager* CSkinObjManager::GetHinstance()
{
    if ( NULL == m_pObjMgr )
    {
        m_pObjMgr = new CSkinObjManager();
    }

    return m_pObjMgr;
}

HSKINHWND CSkinObjManager::AddObject( CSkinWindowBase* pObj )
{
    if ( NULL != pObj )
    {
        ::EnterCriticalSection( &m_csHwnd );
        HSKINHWND hSkinHwnd = ++m_hNextHwnd;
        m_mapObj.insert( std::make_pair( hSkinHwnd, pObj ) );
        ::LeaveCriticalSection( &m_csHwnd );
        return hSkinHwnd;
    }

    return NULL;
}

CSkinWindowBase* CSkinObjManager::FindObject( HSKINHWND uID )
{
    CSkinWindowBase* pSkinObject = NULL;
    ::EnterCriticalSection( &m_csHwnd );
    pSkinObject = m_mapObj[uID];
    ::LeaveCriticalSection( &m_csHwnd );
    return pSkinObject;
}

std::map<HSKINHWND, CSkinWindowBase*>* CSkinObjManager::GetObjectMap()
{
    return &m_mapObj;
}

CSkinWindowBase* CSkinObjManager::CreateObject( LPCTSTR lpszNodeName )
{
    return m_SkinObjEnginer.CreateUdtSkinObject( lpszNodeName );
}
